import wget
import os
import os.path
from s2c.engine.system_info import SystemInfo
from s2c.rules.conf import REGISTRY_URL, SYS_BASE


# Downloader 文件下载器
class Downloader:
    def __init__(self, out='./', url=REGISTRY_URL):
        self.registry = url  # 文件库url， git仓库
        self.out = out  # 输出目录
        info = SystemInfo()  # 依赖系统信息
        self.file_name = info.file_name(dict_type=SYS_BASE)
        self.process_name = info.process_name(dict_type=SYS_BASE)
        self.target_file_name = ''
        self.target_process_name = ''

        self.need_target = info.need_target()
        if self.need_target:
            self.target_file_name = info.file_name(is_target=True, dict_type=SYS_BASE)
            self.target_process_name = info.process_name(is_target=True, dict_type=SYS_BASE)

    def dump(self):
        print('registry =' + self.registry)
        print('file_name =' + self.file_name)
        print('process_name =' + self.process_name)
        print('need_target =' + str(self.need_target))
        print('  target_file_name =' + self.target_file_name)
        print('  target_process_name =' + self.target_file_name)

    # 下载
    def down(self, file_name, is_cover=True):
        full_path = self.registry + file_name
        print('\n 开始下载： ' + full_path)

        # 先删除原有的文件
        if is_cover:
            if os.path.exists(file_name):
                os.remove(file_name)
        try:
            wget.download(full_path, self.out)
        except Exception as e:
            print('\n 下载 ' + file_name + ' 出错.', e)
            return
        print('\n ' + file_name + ' 下载完成.')

    # 下载所有
    def down_all(self):
        # 下载文件系统指纹库
        self.down(self.file_name)
        # 下载进程指纹
        self.down(self.process_name)

        # 下载 target 文件指纹库
        if self.need_target:
            self.down(self.target_file_name)
            self.down(self.target_process_name)


# end class

if __name__ == "__main__":
    Downloader().down('openeuler_20.03_x86_64_file.base.json')
